package cn.jjxx.core.utils;

import java.util.ArrayList;
import java.util.List;

import cn.jjxx.core.common.entity.ZtreeEntity;

/**
 * @Title: TreeBuilder.java .<br>
 * @Package cn.jjxx.core.utils .<br>
 * @Description: list转换成树的工具诶 .<br>
 * @author 郑成功 .<br>
 * @email a876459952@qq.com .<br>
 * @date 2018-5-19 上午8:41:57.<br>
 * @version V1.0.<br>
 */
public class TreeBuilder {

	/**
	 * @Description: 两层循环实现建树  .<br>
	 * @param ztreeList 传入的树节点列表   .<br>
	 * @author 郑成功 .<br>
	 * @date 2018-5-19 上午8:42:33.<br>
	 */
    public static List<ZtreeEntity> bulid(List<ZtreeEntity> ztreeList) {  
        List<ZtreeEntity> trees = new ArrayList<ZtreeEntity>();  
        for (ZtreeEntity zt : ztreeList) {  
        	if(!StringUtils.isNotEmpty(zt.getPid())) {  
                trees.add(zt);  
            }  
            for (ZtreeEntity it : ztreeList) {  
                if (StringUtils.isNotEmpty(it.getPid())&&it.getPid().equals(zt.getId())) {  
                    if (zt.getChildren() == null) {  
                    	zt.setChildren(new ArrayList<ZtreeEntity>());  
                    }  
                    zt.getChildren().add(it);  
                }  
            }  
        }  
        return trees;  
    }  
  
    /**
     * @Description: 使用递归方法建树  .<br>
     * @param ztList 传入的树节点列表   .<br>
     * @author 郑成功 .<br>
     * @date 2018-5-19 上午8:43:01.<br>
     */
    public static List<ZtreeEntity> buildByRecursive(List<ZtreeEntity> ztList) {  
        List<ZtreeEntity> trees = new ArrayList<ZtreeEntity>();  
        for (ZtreeEntity zt : ztList) {  
            if(!StringUtils.isNotEmpty(zt.getPid())) {  
                trees.add(findChildren(zt,ztList));  
            }  
        }  
        return trees;  
    }  
  
    /**
     * @Description: 递归查找子节点  .<br>
     * @param ztree 当前节点   .<br>
     * @param ZtreeEntitys 传入的树节点列表   .<br>
     * @author 郑成功 .<br>
     * @date 2018-5-19 上午8:43:32.<br>
     */
    public static ZtreeEntity findChildren(ZtreeEntity ztree,List<ZtreeEntity> ZtreeEntitys) {  
        for (ZtreeEntity it : ZtreeEntitys) {  
            if(ztree.getId().equals(it.getParentId())) {  
                if (ztree.getChildren() == null) {  
                	ztree.setChildren(new ArrayList<ZtreeEntity>());  
                }  
                ztree.getChildren().add(findChildren(it,ZtreeEntitys));  
            }  
        }  
        return ztree;  
    }
}
